//
//  LXJEmoticonKeyBoardEmoticon.swift
//  XJWeiBo
//
//  Created by 李旭杰 on 2017/4/7.
//  Copyright © 2017年 李旭杰. All rights reserved.
//

import UIKit

/// 表情键盘的表情区域

/// 重用标记
let EmoticonKeyBoardEmoticonCellID = "EmoticonKeyBoardEmoticonCellID"

class LXJEmoticonKeyBoardEmoticon: UICollectionView {
    // MARK: 属性
    var scrollClosure: ((IndexPath) -> ())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        
        /// 界面加载
        setupUI()
    }
    
    /// 不使用 XIB 加载
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 页面搭建
    fileprivate func setupUI() -> Void {
        /// 设置背景颜色
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        /// 注册单元格
        self.register(LXJEmoticonKeyBoardEmoticonCell.self, forCellWithReuseIdentifier: EmoticonKeyBoardEmoticonCellID)
        
        /// 设置数据源和代理对象
        self.dataSource = self
        self.delegate = self
        
    }
}

// MARK: UICollectionView的数据源的方法
extension LXJEmoticonKeyBoardEmoticon: UICollectionViewDataSource, UICollectionViewDelegate{
    /// 组数量
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return LXJEmoticonToolManager.sharedManager.allEmoticonArray.count
    }
    
    /// 每组的数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return LXJEmoticonToolManager.sharedManager.allEmoticonArray[section].count
    }
    
    ///  cell 的样式
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonKeyBoardEmoticonCellID, for: indexPath) as! LXJEmoticonKeyBoardEmoticonCell
        /// 数据源赋值
        cell.emoticonDataSource = LXJEmoticonToolManager.sharedManager.allEmoticonArray[indexPath.section][indexPath.item]
        return cell
    }
    
    /// 在滚动表情页面的时候切换至对应的摁扭
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        /// 获取水平方向的内容的中心点
        let contentCenterX = scrollView.contentOffset.x + scrollView.width * 0.5
        /// 根据内容中心获取cell对应的indexpath
        if let indexPath = self.indexPathForItem(at: CGPoint(x: contentCenterX, y: scrollView.height * 0.5)) {
            /// 执行滑动的闭包
            scrollClosure?(indexPath)
        }
    }
}

// MARK: UICollectionViewCell
class LXJEmoticonKeyBoardEmoticonCell: UICollectionViewCell{
    // MARK: 控件的懒加载
    fileprivate lazy var emoticonButtonArray: [UIButton] = [UIButton]()
    
    /// 删除摁扭
    fileprivate lazy var deleteButton: UIButton = {
        let button = UIButton()
        /// 设置图片
        button.setImage(UIImage(named: "compose_emotion_delete"), for: .normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), for: .highlighted)
        /// 监听摁扭的点击事件
        button.addTarget(self, action: #selector(deleteEmoticonAction), for: .touchUpInside)
        return button
    }()
    
    /// 表情数据
    var emoticonDataSource: [LXJEmoticon]? {
        didSet{
            guard let currentEmoticon = emoticonDataSource else {
                return
            }
            
            /// 隐藏表情图标
            for button in emoticonButtonArray {
                button.isHidden = true
            }
            
            for (index, emoticon) in currentEmoticon.enumerated() {
                /// 获取摁扭
                let button = emoticonButtonArray[index]
                /// 显示摁扭
                button.isHidden = false
                /// 判断表情类型
                if emoticon.type == "1" {/// emoji表情
                    button.setTitle((emoticon.code! as NSString).emoji(), for: .normal)
                    /// 因此图片表情
                    button.setImage(nil, for: .normal)
                }else{
                    /// 表示这个是图片表情
                    button.setImage(UIImage(named: emoticon.path!), for: .normal)
                    /// 因此 Emoji 表情
                    button.setTitle(nil, for: .normal)
                }
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        /// 界面加载
        setupUI()
    }
    
    /// 不使用 XIB 加载
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 页面搭建
    fileprivate func setupUI() -> Void {
        /// 添加子控件
        addChildEmoticonButton()
        /// 添加摁扭
        contentView.addSubview(deleteButton)
    }
    
    /// 添加子摁扭
    fileprivate func addChildEmoticonButton() {
        for _ in 0..<20 {
            let button = UIButton()
            /// 设置摁扭字体的大小
            button.titleLabel?.font = UIFont.systemFont(ofSize: 36)
            /// 添加子控件
            contentView.addSubview(button)
            /// 追加到摁扭数组中
            emoticonButtonArray.append(button)
        }
    }
    
    /// 调节子控件的布局信息
    override func layoutSubviews() {
        super.layoutSubviews()
        /// 设置摁扭的宽
        let buttonWidth = width / 7
        
        /// 设置摁扭的高度
        let buttonHeight = height / 3
        
        /// 设置每一个摁扭的位置信息
        for (index, button) in emoticonButtonArray.enumerated() {
            /// 获取列索引
            let rowIndex = CGFloat(index % 7)
            
            /// 获取行索引
            let cokIndex = CGFloat(index / 7)
            
            /// 设置 X 坐标
            button.x = buttonWidth * rowIndex
            /// 设置 Y 坐标
            button.y = buttonHeight * cokIndex
            
            /// 设置摁扭的大小
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
        }
        
        /// 设置删除摁扭的布局
        deleteButton.x = width - buttonWidth
        deleteButton.y = height - buttonHeight
        deleteButton.size = CGSize(width: buttonWidth, height: buttonHeight)
    }
    
    // MARK: 摁扭的点击事件
    @objc fileprivate func deleteEmoticonAction () {
        /// 发送通知给控制器进行文本删除操作
        NotificationCenter.default.post(name: NSNotification.Name("DidSelectedDeleteEmoticonNotification"), object: nil)
    }
}
